package com.lijz.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class LogServiceImp implements ILogService {
	Logger logger = LoggerFactory.getLogger(LogServiceImp.class);
	@Autowired
	protected MongoTemplate mongoTemplate;

	@Override
	public String writeLog(String userId, String token, SysLog log, Long timeStamp) {
		String collectionName = getCollectionName();
		long start = System.currentTimeMillis();
		mongoTemplate.save(log, collectionName);
		logger.debug("mongodb save 执行时间：" + (System.currentTimeMillis() - start));
		return log.getLogId() + ":" + collectionName;
	}

	@Override
	public void updateLog(String logId, SysLog log) {
		if (logId == null) {    //切面出异常时，处理代码
			logger.debug("----logId为空----");
			String collectionName = getCollectionName();
			mongoTemplate.save(log, collectionName);
			return;
		}
		String[] logIdAndcollectionName = logId.split(":");
		logId = logIdAndcollectionName[0];
		String collectionName = logIdAndcollectionName[1];

		Query query = new Query(Criteria.where("logId").is(Long.valueOf(logId)));
		long start = System.currentTimeMillis();
		SysLog templateOne = mongoTemplate.findOne(query, SysLog.class, collectionName);
		logger.debug("mongodb findOne 执行时间：" + (System.currentTimeMillis() - start));
		if (templateOne == null) {
			mongoTemplate.save(log, collectionName);
		} else {
			Update update = new Update();
			update.set("type", log.getType());
			update.set("exception", log.getException());
			update.set("timeout", log.getTimeout());
			update.set("resultParams", log.getResultParams());
			long start1 = System.currentTimeMillis();
			mongoTemplate.updateMulti(query, update, SysLog.class, collectionName);
			logger.debug("mongodb updateMulti 执行时间：" + (System.currentTimeMillis() - start1));
		}
	}

	@Override
	public Object getLog() {
		return null;
	}

	private String getCollectionName() {
		return "loginfo_" + LocalDate.now();
	}
}
